package com.admin.interfaces.web;

import com.admin.domain.media.MediaException;
import com.admin.domain.media.MediaNotFoundException;
import com.admin.domain.media.MediaStorage;
import com.admin.domain.modle.AjaxResponse;
import com.foxinmy.weixin4j.util.NameValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * 处理文件上传
 *
 * @author jinyu(foxinmy@gmail.com)
 * @className MediaController
 * @date 2017年4月13日
 * @see
 * @since JDK 1.7
 */
@Controller
@RequestMapping("/media")
public class MediaController extends BaseController {
    @Autowired
    @Qualifier("qnMediaStorage")
    private MediaStorage<?> mediaStorage;

    @GetMapping("/get/{filename:.+}")
    @ResponseBody
    public ResponseEntity<InputStream> get(@PathVariable String filename) {
        InputStream is = mediaStorage.load(filename);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                .body(is);
    }

    @ResponseBody
    @PostMapping("/put")
    public AjaxResponse put(@RequestParam("file") MultipartFile file) {
        NameValue nv = mediaStorage.store(file);
        return AjaxResponse.success(nv);
    }

    @ExceptionHandler(MediaNotFoundException.class)
    public ResponseEntity<?> handleMediaNotFound(MediaNotFoundException exc) {
        return ResponseEntity.notFound().build();
    }

    @ExceptionHandler(MediaException.class)
    public AjaxResponse handleException(MediaException exc) {
        return AjaxResponse.error("system error");
    }
}
